package org.deyang.tools.amazon.services;


import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.logging.Logger;

import org.deyang.tools.amazon.exceptions.ImageFetchFailException;

import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.Image.Format;
import com.google.appengine.api.images.ImagesServiceFactory;



public class ImageFormItem {
	private static final Logger log = Logger.getLogger(ImageFormItem.class.getName());
	
	private Image image;
	private byte[] imageData  = new byte[0];
	
	
	public ImageFormItem(String imageURL) throws ImageFetchFailException{
		// target本地地址   
		int HttpResult = 0; //服务器返回的状态   
		try {
			URL url = new URL(imageURL); //创建URL   
			URLConnection urlconn = url.openConnection(); // 试图连接并取得返回状态码
			urlconn.connect();   
			HttpURLConnection httpconn = (HttpURLConnection) urlconn;   
			HttpResult = httpconn.getResponseCode();   
			if (HttpResult != HttpURLConnection.HTTP_OK) // 不等于HTTP_OK说明连接不成功
				throw new ImageFetchFailException();
			else {   
				BufferedInputStream bis=new BufferedInputStream(urlconn.getInputStream());   
				
				byte[] buffer = new byte[1000]; //创建存放输入流的缓冲   
				int num = -1; //读入的字节数
				int sumlength = 0;
				int off = 0;
				while (true) {   
					num = bis.read(buffer); // 读入到缓冲区   
					if (num ==-1){   
						break; //已经读完   
					}  
					sumlength = sumlength + num;
					this.imageData = Arrays.copyOf(this.imageData, sumlength);
					System.arraycopy(buffer, 0, imageData, off, num);
					
					off = off + num;
					
				}

				bis.close();
				
				
				
				this.image = ImagesServiceFactory.makeImage(this.imageData);
				
				//Following statement just to verify whether this image is valid
				this.image.getHeight();
				
			}
		} catch (MalformedURLException e) {
			log.warning(e.getMessage());
			e.printStackTrace();
			throw new ImageFetchFailException();
		} catch (IOException e) {
			log.warning(e.getMessage());
			e.printStackTrace();
			throw new ImageFetchFailException();
		} catch (IllegalArgumentException e) {
			log.warning(e.getMessage());
			e.printStackTrace();
			throw new ImageFetchFailException();
		}

	}
	
	public byte[] getImageData(){
		return this.imageData;
	}
	
	public String getImageContentType(){
		Format format = this.image.getFormat();
		if (format.equals(Format.GIF)) {
			return "image/gif";
		} else if (format.equals(Format.JPEG)) {
			return "image/jpeg";
		} else if (format.equals(Format.PNG)) {
			return "image/png";
		} else if (format.equals(Format.BMP)) {
			return "application/x-bmp";
		}
		return "";
	}
	

}
